/*
 * First class started by the index.html
 */

define(["dojo", "dojo/on", "dojo/topic", "app/nav/GpxReader", "app/nav/GpxParser", 
	"app/nav/MapsDirectionsUtils", "flca/voicenav/srv/VoiceNavServices", "flca/voicenav/dto/PNode",
	"app/nav/Constants", "dojo/domReady!"], 
	function(dojo, on, topic, gpxReader, gpxParser, mapsUtils, services, PNode, C) {
	dojoConfig.locale = 'nl';

	topic.subscribe(C.GPX_RETRIEVED, function(data) {
		drawRoute(data, "#FF0000");
		// drawLocation();
	});

	topic.subscribe(C.FOUND_INTERSECTIONS, function(data) {
		drawIntersection(data, "#1122FF");
	});

	topic.subscribe(C.OPTIMIZEROUTE_LOADED, function(data) {
		drawOptimized(data, "#11FF11");
	});
	
	
	var map, centre;

    var directionDisplay;
    var directionsService = new google.maps.DirectionsService();
    
    
    //-----------  
	function initialize() 
	{
		var myOptions = {
			center : centre,
			zoom : 12,
			mapTypeId : google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(dojo.byId("map_canvas"), myOptions);
		console.log(map);
	};

    //-----------  
	function drawRoute(data, color) 
	{
		console.log("drawing gpx " + data);
		coords = gpxParser.parse(data);
		centre = gpxParser.getCentre();

		initialize();

		var route = new google.maps.Polyline({
			path : coords,
			strokeColor : color,
			strokeOpacity : 1.0,
			strokeWeight : 2
		});

		route.setMap(map);
		// drawLocation(coords[0], map, "#00FFFF");
		// drawLocation(coords[10], map, "#444411");
		
		document.getElementById('hdr').innerHTML = 'done';
		calcRoute(coords);
	};

    //-----------  
	function drawLocation(pnt, map, color) 
	{
		var locationOpts = {
			strokeColor : color,
			strokeOpacity : 0.8,
			strokeWeight : 2,
			fillColor : color,
			fillOpacity : 0.35,
			map : map,
			center : pnt,
			radius : 20
		};
		circle = new google.maps.Circle(locationOpts);
		// circle.setMap(map);
	}

    //-----------  
    function calcRoute(coords) 
    {
 		var i = 0;
 		var goon = true;
 		while (goon) {
	        var start = coords[i];
	        var j = i + 8;
    	    var end = coords[i+8];
	        if (i > coords.length - 8) {
	        	j = coords.length - 2;
	        	end = coords[coords.length - 1];
	        	goon = false;
	        }
 			var waypoints = gpxParser.getWayPoints(i, j, coords);
 			getDirectionsViaWayPoints(start, end, waypoints);
 			i = i + 8;
 		}  
 		
    };

    //-----------  
	function getDirectionsViaWayPoints(start, end, waypoints)
	{
        var request = {
          origin: start,
          destination: end,
          waypoints : waypoints,
          // optimizeWaypoints: true,
          travelMode: google.maps.DirectionsTravelMode.WALKING,  
        };
        
        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
          	document.getElementById('hdr').innerHTML = 'Ok';
          	drawDirections(response);
          } else {
          	document.getElementById('hdr').innerHTML = '** NOT Ok ' + status;          	
          }
        });
	}   
	 
    //-----------  
    function drawDirections(response, color) 
    {
    	var pnts = mapsUtils.getCoordinates(response);
    	var coords = new Array();
    	for(var i = 0; i < pnts.length; i++){
			coords.push(new google.maps.LatLng(pnts[i][0], pnts[i][1]));
			node = new PNode();
			node.id = i;
			node.lat = pnts[i][0] * 1E6;
			node.lng = pnts[i][1] * 1E6;
			if (myCoords.length < 75) {
				myCoords.push(node);
			}
    	}
    	console.log("directions " + coords);
   
   		var route = new google.maps.Polyline({
			path : coords,
			strokeColor : color,
			strokeOpacity : 1.0,
			strokeWeight : 2
		});

		// route.setMap(map);
		//drawRouteInfo(response);
    };
    
    //-----------  
    function drawOptimized(aRoute, color) 
    {
    	var coords = new Array();

    	for (var i = 0; i < aRoute.length; i++) {
    		trkpt = aRoute[i];
			coords.push(new google.maps.LatLng(trkpt.lat, trkpt.lng));
    	}
   
   		console.log("optimized " + coords);
   
   		var route = new google.maps.Polyline({
			path : coords,
			strokeColor : color,
			strokeOpacity : 1.0,
			strokeWeight : 3
		});

		route.setMap(map);
    };
    
    
    
    //-----------  
    function drawIntersection(response) 
    {
    	var coords = new Array();
    	for(var i = 0; i < 	response.length; i++) {
    		pnt = response[i];
			coords.push(new google.maps.LatLng(pnt.lat, pnt.lon));
    	}
 
   		c = response[0];
		centre = new google.maps.LatLng(c.lat, c.lon);
		var myOptions = {
			center : centre,
			zoom : 8,
			mapTypeId : google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(dojo.byId("map_canvas"), myOptions);
  
  		if (coords.length > 100) max = 100; else max = coords.length;
  		
  		for(var i = 0; i <  max; i++) {
   			drawLocation(coords[i], map, "#00FF00");
   		}
   		var route = new google.maps.Polyline({
			path : coords,
			strokeColor : "#00FF00",
			strokeOpacity : 1.0,
			strokeWeight : 2
		});
		// route.setMap(map);
    };
    
	//------------------
	function setup() 
	{
		var myButton = dojo.byId("btn1");
 
		dojo.connect(myButton, "onclick", function(evt){
    		services.optimizeRoute(myCoords);
		});	

		// gpxReader.getGpx('./resources/rondje-stiphout.gpx');
		// gpxReader.getGpx('./resources/barisakker.gpx');
		// gpxReader.getGpx('./resources/amstelgoldrace2008_125_hardfietsen.nl.gpx');
		// gpxReader.getGpx('./resources/nuenen-son-39km.gpx');
		// gpxReader.getGpx('./resources/nuenen-son-39km.gpx');
		// gpxReader.getGpx('./resources/boogies-100km.gpx');
		 gpxReader.getGpx('./resources/luxemburg.gpx');
	}
	
    //-----------  
 
 	myCoords = new Array();
 	
	setup();
});
